<template>
  <div class="container">
      <p>{{userinfo.openId}}</p>
      <div class="userinfo" @click="login" >
        <img :src="userinfo.avatarUrl" alt="">
        <p open-type="getUserInfo">{{userinfo.nickName}}</p>
        
      </div>
      <YearProgress></YearProgress>

      <button v-if="userinfo.openId" class='btn' @click="scanBook">添加图书</button>
      <button open-type="getUserInfo">hahaha</button>
  </div>
</template>

<script>
import qcloud from 'wafer2-client-sdk'
import YearProgress from '@/components/YearProgress'
import {showSuccess, post, showModal} from '@/util'
import config from '@/config'

export default {
  components: {
    YearProgress
  },
  data () {
    return {
      userinfo: {
        avatarUrl: '../../../static/img/unlogin.png',
        nickName: '点击登录'
      }
    }
  },
  methods: {
    async addBook (isbn) {
      const res = await post('/weapp/addbook', {
        isbn,
        openid: this.userinfo.openId
      })
      showModal('添加成功', `${res.title}添加成功`)
    },
    scanBook () {
      wx.scanCode({
        success: (res) => {
          if (res.result) {
            console.log(res)
            this.addBook('9787559627070')
          }
        },
        fail: (res) => {
          console.log(res)
        }
      })
    },
    login () {
      let user = wx.getStorageSync('userinfo')
      const self = this
      if (!user) {
        qcloud.setLoginUrl(config.loginUrl)
        qcloud.login({
          success: function (userinfo) {
            qcloud.request({
              url: config.userUrl,
              login: true,
              success (userRes) {
                showSuccess('登录成功')
                wx.getStorageSync('userinfo', userRes.data.data)
                self.userinfo = userRes.data.data
              }
            })
          },
          fail: function (err) {
            console.log('登录失败', err)
          }
        })
      }
    },
    onShow () {
      // console.log(123)
      let userinfo = wx.getStorageSync('userinfo')
      if (userinfo) {
        this.userinfo = userinfo
      }
    }
  }
  // created () {
  //   this.userinfo = wx.getStorageSync('userinfo')
  // }

}
</script>
<style lang='scss'>
.container{
  padding: 0 30rpx;
  .userinfo{
    margin-top: 100rpx;
    text-align: center;
    img{
      width: 150rpx;
      height:150rpx;
      border-radius: 50%;
    }
  }
}
</style>
